import config from './config'

// 请求封装
const request = (options) => {
  return new Promise((resolve, reject) => {
    const { url, method = 'GET', data, header = {} } = options
    
    wx.request({
      url: `${config.baseURL}${url}`,
      method,
      data,
      header: {
        ...config.header,
        ...header
      },
      timeout: config.timeout,
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data)
        } else {
          reject(res)
          wx.showToast({
            title: '请求失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        reject(err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  })
}

// 封装常用请求方法
export const get = (url, data, header) => {
  return request({
    url,
    method: 'GET',
    data,
    header
  })
}

export const post = (url, data, header) => {
  return request({
    url,
    method: 'POST',
    data,
    header
  })
}

export const put = (url, data, header) => {
  return request({
    url,
    method: 'PUT',
    data,
    header
  })
}

export const del = (url, data, header) => {
  return request({
    url,
    method: 'DELETE',
    data,
    header
  })
}

export default request 